package cate.game.cross;

import cate.common.table.d.GDFunc;
import cate.game.cross.core.CrossSyncAdventure;
import cate.game.cross.msg.CrossHelpInnerMsg;
import cate.game.cross.msg.CrossLambReq;
import cate.game.framework.ModuleMan;
import cate.game.play.part.PlaySide;
import cate.game.role.Role;
import cate.game.role.RoleSnapshot;
import cate.game.util.IntervalCounter;
import cp.solution.rpc.RpcMsgHead;
import easy.java.practice.errorcode.EcResult;

import java.util.*;

public class CrossManager extends ModuleMan {

    public static final String MODULE_NAME = "cross-space";

    /**
     * 跨服成员列表
     */
    private Map<Integer, CrossMember> members;

    protected final IntervalCounter syncTrigger = new IntervalCounter(600 + new Random().nextInt(120) + 1);

    public CrossManager() {

    }

    @Override
    public void initDependent() throws Exception {
        if (members == null) {
            members = new HashMap<>();
        }
        addSelfMember();
        game.rpcRecv().onFireAndForgetTemplate(CrossHelpInnerMsg.SHOW_LAMB, CrossLambReq.class, this::showLamb);
    }

    public CrossMember addSelfMember() {
        CrossMember member = new CrossMember();
        member.worldLevel = game.rank.level.calcWorldLevel();
        member.srvName = game.config.gs.getName();
        member.srvId = game.config.srvId;
        addMember(member);
        return member;
    }

    public int getWorldLevel() {
        return members.getOrDefault(game.config.srvId, addSelfMember()).worldLevel;
    }

    public List<CrossMember> getMemberList() {
        return new ArrayList<>(members.values());
    }

    public void tick() {
        if (syncTrigger.trigger()) {
            addSelfMember();
        }
    }

    public void addMember(CrossMember member) {
        if (member != null) {
            members.put(member.srvId, member);
        }
    }

    /**
     * 同布主线阵容
     */
    public void syncAdventure(Role role) {
        EcResult<PlaySide> r_side = role.getGame().fight.side.createPlaySideByRole(role, GDFunc.ADVENTURE, 1);
        if (!r_side.ok()) {
            return;
        }
        game.rpcSend().fireAndForgetCross(CrossHelpInnerMsg.SYNC_ADVENTURE, new CrossSyncAdventure(role.getUid(), r_side.data));
    }

    /**
     * 同布快照
     */
    public void syncSnapshot(Role role) {
        game.rpcSend().fireAndForgetCross(CrossHelpInnerMsg.SYNC_SNAPSHOT, new RoleSnapshot(role));
    }

    /**
     * 同布快照Group
     */
    public void syncSnapshotGroup(Role role) {
        game.rpcSend().fireAndForgetGroup(CrossHelpInnerMsg.SYNC_SNAPSHOT, new RoleSnapshot(role));
    }

    /**
     * 跨服发送跑马灯
     *
     * @param head 消息头
     * @param req  跑马灯请求
     */
    private void showLamb(RpcMsgHead head, CrossLambReq req) {
        game.notice.lampOnline(null, req.lambId, req.params);
    }
}
